//
//  SEGNewTopicManager.m
//  SEGUhomeSommunitySocial
//
//  Created by 揭婧雯 on 2018/3/28.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGNewTopicManager.h"
#import <SEGPlatform/SEGAdDisplayManager.h>
#import <SEGPlatform/SEGSquareViewModel.h>

@interface SEGNewTopicManager ()
@property (nonatomic, assign) NSInteger totalCommentPage;
@property (nonatomic, assign) NSInteger adverIndex;
@end

@implementation SEGNewTopicManager
#pragma mark - 话题列表
- (void)requestpictoriaListByisHot:(NSString*)isHot
                         praiseNum:(NSString*)praiseNum
                            PageNo:(NSInteger)pageNo
                          PageSize:(NSInteger)pageSize
                          Finished:(SEGRequestCallBack)finished
{
    SEGProfileModel* Account = [SEGProfileManager sharedManager].profile;
    
    NSDictionary* params = @{
                             @"isHot" : isHot,
                             @"praiseNum" : praiseNum,
                             @"pageNo" : @(pageNo),
                             @"pageSize" : @(pageSize),
                             @"provinceId" : Account.provinceId,
                             @"cityId" : Account.cityId,
                             @"regionId" : Account.region,
                             @"communityId" : kAccountCommunityID
                             };
    
    __block NSInteger _page = pageNo;
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/pictorial/talkList.json",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        NSDictionary* dicData = [result valueForKey:@"data"];
        if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
            finished(NO, codeType, errorMessage);
            return;
        }
        NSArray* pictorialList = [dicData valueForKey:@"pictorialList"];
        
        if (pictorialList && pictorialList.count <= 0) {
            
            finished(NO, codeType, @"已经到底了！"); //数据返回正常，但是数据为空
            return;
        }
        
        NSMutableArray* arrM = [NSMutableArray arrayWithCapacity:pictorialList.count];
        
        for (NSDictionary* dic in pictorialList) {
            
            SEGTopicListModel* _model = [SEGTopicListModel initWithDictionary:dic];
            
            [arrM addObject:_model];
        }
        
        if (_page == 1) { //顶部刷新
            self.seg_segtopiclistmodel = @[];
        }
        
        NSMutableArray* _tmpData = [NSMutableArray arrayWithArray:self.seg_segtopiclistmodel];
        [_tmpData addObjectsFromArray:arrM];
        
        self.seg_segtopiclistmodel = _tmpData;
        
        finished(YES, codeType, errorMessage);
        
    }];
}


/**
 * 获取话题详情
 * @author Wendy
 * @param id  主键id
 */
- (void)requestTopicDetailWithId:(NSString *)Id
                        finished:(SEGRequestCallBack)finished
{
    NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:Id, @"id", nil];
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/queryPictorialDetailById",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        NSDictionary* dicData = [result valueForKey:@"data"];
        if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        self.topicDetailModel = [SEGSharedTopicDetailModel initWithDictionary:dicData];
        
        finished(YES, codeType, errorMessage);
    }];
}

// 话题评论列表
- (void)requestTopicCommentListByObjId:(NSString*)objId
                                    objType:(NSString*)objType
                                    pgcType:(NSInteger)pgcType
                                     pageNo:(NSInteger)pageNo
                                   pageSize:(NSInteger)pageSize
                                   Finished:(SEGRequestCallBack)finished
{
    if (!self.totalCommentPage) self.totalCommentPage = 1;
    if (pageNo > self.totalCommentPage) return;
    NSDictionary* params = @{
                             @"objId" : objId,
                             @"objType" : objType,
                             @"pageNo" : @(pageNo),
                             @"pageSize" : @(pageSize),
                             @"userId" : kAccountUserID
                             };    
    __block NSInteger _pageNo = pageNo;
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/",kCMS_api,@"/quiz/findPictorialQuizList.json",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if ([result valueForKey:@"data"] && [[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary* dicData = [result valueForKey:@"data"];
            
            NSInteger totalPage = [[dicData valueForKey:@"totalPage"] integerValue];
            self.totalCommentPage = totalPage;
            
            NSArray* pictQuizList = [dicData valueForKey:@"pictQuizList"];
            
            if (_pageNo != 1 && [pictQuizList isKindOfClass:[NSArray class]] && pictQuizList.count == 0) {
                finished(YES, codeType, @"没有更多的数据！");
                return;
            }
            
            NSString* userIds = @"";
            NSMutableArray* arrM = [NSMutableArray arrayWithCapacity:pictQuizList.count];
            
            
            for (NSDictionary* dic in pictQuizList) {
                
                SEGFindQuizListByQuizTypeModel* _model = [SEGFindQuizListByQuizTypeModel yy_modelWithJSON:dic];
                _model.quizContent1 = _model.quizContent;
                [arrM addObject:_model];
                userIds = [userIds stringByAppendingString:[NSString stringWithFormat:@",%@",_model.userId]];
            }
            
            // 4.9.6 需要对话题数据做过滤，去掉本地举报的数据
            NSDictionary *reportDictionary = [[NSUserDefaults standardUserDefaults] objectForKey:kNeighborhoodReportedArray];
            if (reportDictionary && [reportDictionary isKindOfClass:[NSDictionary class]]) {
                NSMutableArray *reportArray = [reportDictionary objectForKey:kAccountUserID];
                if (reportArray.count > 0) {
                    NSMutableArray *requestFilterArray = [NSMutableArray array];
                    [arrM enumerateObjectsUsingBlock:^(SEGFindQuizListByQuizTypeModel * _Nonnull requestObj, NSUInteger idx, BOOL * _Nonnull stop) {
                        __block BOOL isReported = NO; //标记是否被举报
                        [reportArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull subReportDic, NSUInteger idx, BOOL * _Nonnull stop) {
                            NSString *reportObjType = subReportDic[@"objType"];
                            NSString *reportObjId = subReportDic[@"objId"];
                            if ([requestObj.quizId isEqualToString:reportObjId] && [requestObj.objType isEqualToString:reportObjType]) {
                                isReported = YES;
                                *stop = YES;
                            }
                        }];

                        if (!isReported) {
                            [requestFilterArray addObject:requestObj];
                        }
                    }];
                    arrM = [requestFilterArray mutableCopy];
                    // TODO:过滤之后没有数据如何处理
                }

            }

            if (_pageNo == 1) { //顶部刷新
                self.topicCommentList = @[];
                self.adverIndex = 0;
            }
            // 对请求到的数据做内容显示逻辑整理
            [self seg_findQuizListLogic:arrM];
            
            /*
             插入广告逻辑
             1.M为一组，每组第N个位置展示广告;
                 eg.M=1 N=1，那么数据为：广告、数据、广告、数据.....
             2.M>0 N>0 M>=N
             3.当前组不够M个的时候，不展示广告
             4.只有图文话题列表插入广告 文字话题列表不加
            */
            SEGAdDisplayModel *adDisplayModel = [[SEGAdDisplayManager shared] getLoopAdDisplayModel:SEGAD_ImageTopicType];
            if (pgcType == 2 && adDisplayModel && adDisplayModel.groupCount > 0 && adDisplayModel.showAdvCount > 0 && adDisplayModel.groupCount >= adDisplayModel.showAdvCount) {
                NSInteger __block currentIndex = 1;
                NSInteger __block lastGroupIndex = arrM.count / adDisplayModel.groupCount * adDisplayModel.groupCount;
                NSMutableArray<SEGFindQuizListByQuizTypeModel *> *handleQuizList = [NSMutableArray array];
                [arrM enumerateObjectsUsingBlock:^(SEGFindQuizListByQuizTypeModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if (currentIndex == adDisplayModel.showAdvCount && idx < lastGroupIndex) {
                        SEGFindQuizListByQuizTypeModel *adModel = [[SEGFindQuizListByQuizTypeModel alloc] init];
                        adModel.isAdvertisement = YES;
                        adModel.adverIndex = self.adverIndex;
                        self.adverIndex ++;
                        [handleQuizList addObject:adModel];
                    }
                    [handleQuizList addObject:obj];
                    
                    // 计算下标 超过一组就重置
                    currentIndex ++;
                    if (currentIndex > adDisplayModel.groupCount) {
                        currentIndex = 1;
                    }
                }];
                arrM = [handleQuizList mutableCopy];
            }
            
            NSMutableArray* _tmpData = [NSMutableArray arrayWithArray:self.topicCommentList];
            [_tmpData addObjectsFromArray:arrM];
            
            self.topicCommentList = _tmpData;
            
            if ([userIds length] > 0) {
                userIds = [userIds substringFromIndex:1];
            }
            finished(YES, codeType, userIds);
        }
        //finished(isSuccessed, codeType, errorMessage);
    }];
}

//内容显示逻辑整理
- (void)seg_findQuizListLogic:(NSArray<SEGFindQuizListByQuizTypeModel*>*)arr
{
    [arr enumerateObjectsUsingBlock:^(SEGFindQuizListByQuizTypeModel* _Nonnull obj, NSUInteger idx, BOOL* _Nonnull stop) {
        
        if ([obj.objType isEqualToString:@"5"]) { // 话题
            obj.LinkType = SEGFindQuizListByQuizTypeModelLinkTypeTOPIC;
            if ([obj.linkTitle length] > 0) {
                obj.linkTitle = [NSString stringWithFormat:@"#%@#", obj.linkTitle];
                obj.quizContent = [NSString stringWithFormat:@"%@ %@", obj.linkTitle, obj.quizContent];
            }
        }
        else if ([obj.objType isEqualToString:@"11"]) { // 帮帮中的赞赞
            obj.LinkType = SEGFindQuizListByQuizTypeModelLinkTypePRAISE;
            obj.userName = @"帮帮正能量";
            obj.communityName = [NSString stringWithFormat:@"来自 %@",kAppName];
            obj.isAuth = @(3);
            obj.linkTitle = @"#物业服务#";
            obj.quizContent = [NSString stringWithFormat:@"%@ %@\n点击查看奖状", obj.linkTitle, obj.quizContent];
        }
        else if ([obj.linkTitle length] > 0 && [obj.linkUrl length] > 0) { //原文链接
            obj.LinkType = SEGFindQuizListByQuizTypeModelLinkTypeLINK;
            obj.quizContent = [NSString stringWithFormat:@"原文 %@", obj.quizContent];
        }
        else { //原文无链接
            obj.LinkType = SEGFindQuizListByQuizTypeModelLinkTypeNO;
        }
    }];
}

#pragma mark - 聊聊
/**
 * 聊聊广场-置顶
 * @author Sam
 */
- (void)requestTalkFinished:(SEGNetworkReponse)finished {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/top",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if(!isSuccessed){
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        NSDictionary *data = [result valueForKey:@"data"];
        if (!data || ![data isKindOfClass:[NSDictionary class]]) {
            // 数据错误不给提示
            finished(NO,nil,codeType,@"");
            return;
        }
        
        NSArray *topic = [data valueForKey:@"topic"];
        if (!topic || ![topic isKindOfClass:[NSArray class]]) {
            // [bugfix 31701]数据错误不给提示
            finished(NO,nil,codeType,@"");
            return;
        }
        
        NSMutableArray *arrM = [NSMutableArray array];
        [topic enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGSquareViewModel* data = [SEGSquareViewModel yy_modelWithDictionary:obj];
            data.type = SEGEnumSquareViewType_Square;
            [arrM addObject:data];
        }];

        _pgcTopSource = [NSArray arrayWithArray:arrM];
        
        finished(isSuccessed,result, codeType, errorMessage);
        
    }];
}

/**
 * 聊聊广场 - 热聊
 * @author Sam
 */
-(void)requestTalkHotTopicWithPageNo:(NSInteger)pageNo Finished:(SEGNetworkReponse)finished{
    
    NSDictionary* params = @{
                             @"pageNo" : @(pageNo),
                             @"pageSize" : @(15)
                             };
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v2/hotTopic",nil];

    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if(!isSuccessed){
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        NSDictionary *data = [result valueForKey:@"data"];
        if (!data || ![data isKindOfClass:[NSDictionary class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        
        NSArray *topic = [data valueForKey:@"topic"];
        if (!topic || ![topic isKindOfClass:[NSArray class]]) {
            finished(NO,nil,codeType,errorMessage);
            return;
        }
        //[NSArray yy_modelArrayWithClass:[SEGSquareViewModel class] json:topic];
        
        NSMutableArray *arrM = [NSMutableArray array];
        [topic enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGSquareViewModel* data = [SEGSquareViewModel yy_modelWithDictionary:obj];
            data.type = SEGEnumSquareViewType_Square;
            [arrM addObject:data];
        }];
        
        NSMutableArray *oldData = pageNo == 1 ? [NSMutableArray array]:[NSMutableArray arrayWithArray:_pgcHotTopicSource];
        if(!oldData) oldData = [NSMutableArray array];
        [oldData addObjectsFromArray:arrM];
        _pgcHotTopicSource = [NSArray arrayWithArray:oldData];
        
        finished(isSuccessed,result, codeType, errorMessage);
        return;
    }];
}

#pragma mark - getter
- (NSArray<SEGTopicListModel*>*)seg_segtopiclistmodel
{
    if (!_seg_segtopiclistmodel) {
        _seg_segtopiclistmodel = [NSArray array];
    }
    return _seg_segtopiclistmodel;
}

- (SEGSharedTopicDetailModel *)topicDetailModel
{
    if (!_topicDetailModel) {
        _topicDetailModel = [[SEGSharedTopicDetailModel alloc] init];
    }
    return _topicDetailModel;
}

- (NSArray<SEGFindQuizListByQuizTypeModel*>*)topicCommentList
{
    if (!_topicCommentList) {
        
        _topicCommentList = [NSArray array];
    }
    
    return _topicCommentList;
}

@end
